<template>
  <div>
    <el-form ref="ruleForm" :model="form" label-width="100px" :rules="rules">
      <strong class="title">商品基本信息</strong>
      <el-row>
        <el-col :span="6">
          <el-form-item label="商家名称" prop="companyName">
            <el-input v-model="form.companyName" placeholder="商家名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品名称" prop="itemDesc">
            <el-input v-model="form.itemDesc" placeholder="商品名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品品牌" prop="brandName">
            <el-input v-model="form.brandName" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品类" prop="category">
            <el-cascader
              v-model="form.category"
              :options="categoryList"
              @change="handleCategoryChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="SPU编码" prop="spuCode">
            <el-input v-model="form.spuCode" placeholder="SPU编码" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="SPU名称" prop="spuDesc">
            <el-input v-model="form.spuDesc" placeholder="SPU名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品条码" prop="barCode">
            <el-input v-model="form.barCode" placeholder="商品条码" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品编码" prop="itemCode">
            <el-input v-model="form.itemCode" placeholder="商品编码" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="SKC编码" prop="skcCode">
            <el-input v-model="form.skcCode" placeholder="SKC编码" :disabled="form.category.length == 0" @blur="handleBlur" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="SKC名称" prop="skcDesc">
            <el-input v-model="form.skcDesc" placeholder="SKC名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="保质期" prop="expireDate">
            <el-input-number
              v-model="form.expireDate"
              controls-position="right"
              :precision="0"
              placeholder="单位天"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="重量" prop="weight">
            <el-input-number
              v-model="form.weight"
              controls-position="right"
              :precision="2"
              placeholder="重量"
              :min="0"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="商品长" prop="length">
            <el-input-number
              v-model="form.length"
              controls-position="right"
              :precision="2"
              placeholder="单位厘米"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品宽" prop="width">
            <el-input-number
              v-model="form.width"
              controls-position="right"
              :precision="2"
              placeholder="单位厘米"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品高" prop="high">
            <el-input-number
              v-model="form.high"
              controls-position="right"
              :precision="2"
              placeholder="单位厘米"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="体积" prop="volume">
            <el-input-number
              v-model="form.volume"
              controls-position="right"
              :precision="2"
              placeholder="单位平方厘米"
              :min="0"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="包装量" prop="packageSize">
            <el-input v-model="form.packageSize" placeholder="包装量" />
          </el-form-item>
        </el-col>
      </el-row>
      <strong class="title">商品价格</strong>
      <el-row>
        <el-col :span="6">
          <el-form-item label="吊牌价" prop="tagPrice">
            <el-input-number
              v-model="form.tagPrice"
              controls-position="right"
              :precision="2"
              placeholder="吊牌价"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购价格" prop="purchasePrice">
            <el-input-number
              v-model="form.purchasePrice"
              controls-position="right"
              :precision="2"
              placeholder="采购价格"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="销售价格" prop="sellPrice">
            <el-input-number
              v-model="form.sellPrice"
              controls-position="right"
              :precision="2"
              placeholder="销售价格"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="成本价格" prop="costPrice">
            <el-input-number
              v-model="form.costPrice"
              controls-position="right"
              :precision="2"
              placeholder="成本价格"
              :min="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <strong class="title">商品属性</strong>
      <el-row type="flex" style="flex-wrap: wrap" justify="start">
        <el-col v-for="item in productAttrList" :key="item.attributeCode" :span="6">
          <el-form-item
            v-if="item.attributeCode == 'color'"
            label="颜色"
            prop="colorCode"
            :rules="{required: true, message: '请选择颜色', trigger: 'change'}"
          >
            <el-select
              v-model="form.colorCode"
              placeholder="请选择颜色"
              :disabled="colorDisable"
              filterable
              remote
              :remote-method="(keyWord) => fetchAttrListByKeyword(keyWord, item.attributeCode)"
              @change="handleColorChange(item.attributeValues)"
            >
              <el-option
                v-for="attr in item.attributeValues"
                :key="attr.key"
                :value="attr.key"
                :label="attr.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-else-if="item.attributeCode == 'size'"
            label="尺寸"
            prop="sizeCode"
            :rules="{required: true, message: '请选择尺寸', trigger: 'change'}"
          >
            <el-select
              v-model="form.sizeCode"
              placeholder="请选择尺寸"
              filterable
              remote
              :remote-method="(keyWord) => fetchAttrListByKeyword(keyWord, item.attributeCode)"
              @change="handleSizeChange(item.attributeValues)"
            >
              <el-option
                v-for="attr in item.attributeValues"
                :key="attr.key"
                :value="attr.key"
                :label="attr.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-else-if="item.attributeCode == 'season'"
            label="季节"
            prop="seasonType"
            :rules="{required: true, message: '请选择季节', trigger: 'change'}"
          >
            <el-select
              v-model="form.seasonType"
              placeholder="请选择季节"
              filterable
              remote
              :remote-method="(keyWord) => fetchAttrListByKeyword(keyWord, item.attributeCode)"
            >
              <el-option
                v-for="attr in item.attributeValues"
                :key="attr.key"
                :value="attr.value"
                :label="attr.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-else-if="item.attributeCode == 'material'"
            label="材质"
            prop="material"
          >
            <el-select
              v-model="form.material"
              placeholder="请选择材质"
              filterable
              remote
              :remote-method="(keyWord) => fetchAttrListByKeyword(keyWord, item.attributeCode)"
            >
              <el-option
                v-for="attr in item.attributeValues"
                :key="attr.key"
                :value="attr.value"
                :label="attr.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-else-if="item.attributeCode == 'sex'"
            label="性别"
            prop="sex"
            :rules="{required: true, message: '请选择性别', trigger: 'change'}"
          >
            <el-select
              v-model="form.sex"
              placeholder="请选择性别"
              filterable
              remote
              :remote-method="(keyWord) => fetchAttrListByKeyword(keyWord, item.attributeCode)"
            >
              <el-option
                v-for="attr in item.attributeValues"
                :key="attr.key"
                :value="attr.value"
                :label="attr.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-else-if="item.attributeCode == 'year'"
            label="年份"
            prop="year"
            :rules="{required: true, message: '请选择年份', trigger: 'blur'}"
          >
            <el-select
              v-model="form.year"
              placeholder="请选择年份"
              filterable
              remote
              :remote-method="(keyWord) => fetchAttrListByKeyword(keyWord, item.attributeCode)"
            >
              <el-option
                v-for="attr in item.attributeValues"
                :key="attr.key"
                :value="attr.value"
                :label="attr.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <strong class="title">商品图片</strong>
      <el-form-item ref="uploadElement" prop="imgList" label="商品图片">
        <el-upload
          ref="upload"
          name="file"
          list-type="picture-card"
          accept="image/*"
          action="https://addr.aikucun.com/v1.0/upload/file"
          :class="{hide: form.imgList.length == 4}"
          :before-upload="beforeUpload"
          :on-remove="handleFileRemove"
          :on-preview="handlePictureCardPreview"
          :on-success="handleFileSuccess"
          :on-change="handleFileChange"
          :limit="4"
          :file-list="form.imgList"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <div style="display: flex; justify-content: center; padding: 20px;">
        <el-button type="primary" @click="handleSure">确定</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { transformData } from '../../../utils/utils'
import { queryCategoryAllList, queryCategoryAttributeBindList, getAttrListByAttrCode } from '../../../api/goods'

export default {
  name: 'ProductCreate',
  data() {
    return {
      categoryList: [],
      productAttrList: [],
      form: {
        companyName: '',
        companyCode: '',
        brandCode: '',
        brandName: '',
        itemCode: '',
        itemDesc: '',
        spuCode: '',
        spuDesc: '',
        skcCode: '',
        skcDesc: '',

        category: [],
        barCode: '',

        tagPrice: undefined,
        purchasePrice: undefined,
        costPrice: undefined,
        sellPrice: undefined,

        width: undefined,
        length: undefined,
        high: undefined,
        volume: undefined,
        weight: undefined,
        expireDate: undefined,

        sex: '',
        seasonType: '',
        year: '',
        material: '',

        colorCode: '',
        colorName: '',
        sizeCode: '',
        size: '',

        imgList: []
      },
      rules: {
        companyName: [
          { required: true, message: '请填写商家名称', trigger: 'blur' }
        ],
        itemCode: [
          { required: true, message: '商品编码为空', trigger: 'blur' }
        ],
        itemDesc: [
          { required: true, message: '请填写商品名称', trigger: 'blur' }
        ],
        brandName: [
          { required: true, message: '请选择商品品牌', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择三级品类', trigger: 'change' }
        ],
        barCode: [
          { required: true, message: '请输入条形码', trigger: 'blur' }
        ],
        skcCode: [
          { required: true, message: '请填写SKC编码', trigger: 'blur' }
        ],
        spuCode: [
          { required: true, message: '请填写SPU编码', trigger: 'blur' }
        ],
        spuDesc: [
          { required: true, message: '请填写SPU名称', trigger: 'blur' }
        ],
        tagPrice: [
          { required: true, message: '请输入吊牌价', trigger: 'blur' }
        ],
        imgList: [
          { required: true, message: '请上传图片' }
        ]
      }
    }
  },
  methods: {
    handleSure() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const { category, imgList, ...rest } = this.form
          const category1 = category && category[0] ? category[0] : ''
          const category2 = category && category[1] ? category[1] : ''
          const category3 = category && category[2] ? category[2] : ''
          const skcAttachmentVOS = imgList.map((item, index) => {
            const newItem = {}
            newItem.attachmentUrl = item.url
            newItem.orderNo = index
            return newItem
          })
          if (skcAttachmentVOS.length < 4) {
            this.$message.error('图片数少于4张')
            return
          }
          const params = { ...rest, category1, category2, category3, skcAttachmentVOS }
          // console.log('params===', params)
          if (this.id) {
            this.productUpdate({ ...params, id: this.id })
          } else {
            this.productCreate(params)
          }
        } else {
          return false
        }
      })
    },
    handleBack() {
      this.$refs.ruleForm.resetFields()
      this.$refs.ruleForm.clearValidate()
      this.$router.go(-1)
    },
    handleBlur() {
      if (this.form.skcCode) {
        this.getGoodsInfoBySkcCode(this.form.skcCode)
      }
    },
    // 获取品类数据
    async queryCategoryList() {
      try {
        const resData = await queryCategoryAllList({})
        let { data: { code, message, result }} = resData
        if (code === 0) {
          result = result || []
          const categoryList = transformData(result)
          this.categoryList = categoryList
        } else {
          this.$message.error(message)
        }
      } catch (e) {

      }
    },
    // 获取某格skc下的图片列表
    async getGoodsInfoBySkcCode(skcCode) {
      const { data: { code, message, result }} = await getDetail({ skcCode })
      if (code === 0) {
        const { skc, attList } = result
        if (skc.colorCode) {
          this.colorDisable = true
        }
        this.form.colorCode = skc.colorCode
        this.form.colorName = skc.colorName
        this.form.imgList = attList.map(item => {
          const newItem = {}
          newItem.url = item.attachmentUrl
          newItem.orderNo = item.orderNo
          return newItem
        })
      } else {
        this.$message.warning(message)
      }
    },
    // 根据所选品类获取属性列表
    async fetchProductAttrData(categoryCode) {
      const { data: { code, message, result }} = await queryCategoryAttributeBindList({ categoryCode })
      if (code === 0) {
        this.productAttrList = result || []
      } else {
        this.$message.error(message)
      }
    },
    handleCategoryChange(val) {
      if (val.length === 3) {
        this.fetchProductAttrData(val[val.length - 1])
        this.colorDisable = false
        this.form = {
          ...this.form,
          sex: '',
          seasonType: '',
          year: '',
          material: '',
          colorCode: '',
          colorName: '',
          sizeCode: '',
          size: ''
        }
      } else {
        this.form.category = []
      }
    },
    async productCreate(params) {
      const { data: { code, message, result }} = await createProduct(params)
      if (code === 0) {
        this.$message.success('创建成功')
        this.handleBack()
      } else if (code === 100001) {
        this.showConfirm(params)
      } else {
        this.$message.error(message)
      }
    },
    async productUpdate(params) {
      const { data: { code, message, result }} = await updateProduct(params)
      if (code === 0) {
        this.$message.success('修改成功')
        this.handleBack()
      } else if (code === 100001) {
        this.showConfirm(params)
      } else {
        this.$message.error(message)
      }
    },
    showConfirm(params) {
      this.$confirm(`此商品信息已存在对应的条码，条码为${params.barCode}\n是否确认创建商品？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.id) {
          this.productUpdate({ ...params, confirm: true })
        } else {
          this.productCreate({ ...params, confirm: true })
        }
      }).catch(() => {})
    },
    // 图片上传处理开始
    beforeUpload(file) {
      const isImg = file.type && file.type.indexOf('image/') === 0
      if (!isImg) {
        this.$message.error('请选择图片文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过2MB!')
      }
      return isImg && isLt2M
    },
    handlePictureCardPreview(file) {
      this.picDialogImageUrl = file.url
      this.picDialogVisible = true
    },
    handleFileRemove(file) {
      this.form.imgList = this.form.imgList.filter(item => item.url !== file.url)
    },
    handleFileChange(file, fileList) {
      // if (fileList.length == 4) {
      // this.rules.imgList = []
      // this.$refs['uploadElement'].clearValidate()
      // }
    },
    handleFileSuccess(res, file) {
      const { code, message, data } = res
      if (code === 0) {
        this.form.imgList.push({
          uid: file.uid,
          url: data.filename[0]
        })
      } else {
        this.$message.error(message)
      }
    },
    // 图片上传处理结束
    handleColorChange(list) {
      const data = list.find(item => item.key === this.form.colorCode)
      this.form.colorName = data && data.value ? data.value : ''
    },
    handleSizeChange(list) {
      const data = list.find(item => item.key === this.form.sizeCode)
      this.form.size = data && data.value ? data.value : ''
    },

    // 根据id获取编辑页数据
    async getInfoById(id) {
      const { data: { code, message, result }} = await getEditProductBasicInfo(id)
      let {
        companyCode,
        companyName,
        itemCode,
        itemDesc,
        brandCode,
        brandName,
        category1,
        category2,
        category3,
        skcCode,
        skcDesc,
        spuCode,
        spuDesc,
        barCode,

        expireDate,
        length,
        volume,
        weight,
        width,
        packageSize,

        costPrice,
        purchasePrice,
        sellPrice,
        tagPrice,

        colorCode,
        colorName,
        size,
        sizeCode,

        material,
        sex,
        seasonType,
        year,

        skcAttachmentVOS
      } = result
      const category = [category1, category2, category3]
      skcAttachmentVOS = skcAttachmentVOS || []
      const imgList = skcAttachmentVOS.map(item => {
        const newItem = {}
        newItem.url = item.attachmentUrl
        newItem.orderNo = item.orderNo
        return newItem
      })
      this.form = {
        ...this.form,
        companyCode,
        companyName,
        itemCode,
        itemDesc,
        brandCode,
        brandName,
        category,
        skcCode,
        skcDesc,
        spuCode,
        spuDesc,
        barCode,

        expireDate: expireDate || undefined,
        length: length || undefined,
        volume: volume || undefined,
        weight: weight || undefined,
        width: width || undefined,
        packageSize,

        costPrice: costPrice || undefined,
        purchasePrice: purchasePrice || undefined,
        sellPrice: sellPrice || undefined,
        tagPrice: tagPrice || undefined,

        colorCode,
        colorName,
        size,
        sizeCode,

        material,
        sex,
        seasonType,
        year,
        imgList
      }
      if (category3) {
        this.fetchProductAttrData(category3)
      }
    },
    fetchAttrListByKeyword(keyWord, attributeCode) {
      getAttrListByAttrCode({ attributeCode, attributeValue: keyWord })
        .then(({ data }) => {
          if (data.success) {
            this.productAttrList = this.productAttrList.map(item => {
              if (item.attributeCode === attributeCode) {
                item.attributeValues = data.data
              }
              return item
            })
          }
        })
    },
    init() {
      this.id = ''
      this.colorDisable = false
      this.$refs.ruleForm.resetFields()
      this.$refs.ruleForm.clearValidate()
    }
  }
}
</script>

<style scoped>

</style>
